//
//  MarketShareData.m
//  AppFinaceHD
//
//  Created by Lion on 13-4-7.
//  Copyright (c) 2013年 Lion. All rights reserved.
//

#import "AFMarketNetData.h"

#import "AFNetworking.h"

#import "AFSetting.h"

#import "AFNetManager.h"
#import "AFMarketData.h"

#import "AFDbManager.h"

static AFMarketNetData *afMarketNetData;

static NSDictionary *marketExcodeDict = nil; // 行情种类列表

@implementation AFMarketNetData

+(AFMarketNetData*) manager{
    if (afMarketNetData == nil) {
    @synchronized(self){
        if (afMarketNetData == nil) {
            afMarketNetData = [[self alloc] init];
        }
    }
}
    return afMarketNetData;
}

////////////////////////////////////////////////////////////////////////////////
//****************************************************************************//
////////////////////////////////////////////////////////////////////////////////
#pragma mark - ========== 行情种类 列表 数据 ========== 
// 行情种类列表
-(NSDictionary*)marketExcodeDict{
    
    if (marketExcodeDict != nil) {
        return marketExcodeDict;
    }
    
    marketExcodeDict = @{AF_K_MARKET_KEY_CUSTOM: AF_K_MARKET_KEY_CUSTOM_NAME,
                       AF_K_MARKET_KEY_WGJS: AF_K_MARKET_KEY_WGJS_NAME,
                       AF_K_MARKET_KEY_WH: AF_K_MARKET_KEY_WH_NAME,
                       AF_K_MARKET_KEY_LME: AF_K_MARKET_KEY_LME_NAME,
                       AF_K_MARKET_KEY_GJZS: AF_K_MARKET_KEY_GJZS_NAME,
                       AF_K_MARKET_KEY_NYMEX: AF_K_MARKET_KEY_NYMEX_NAME,
                       AF_K_MARKET_KEY_COMEX: AF_K_MARKET_KEY_COMEX_NAME,
                       AF_K_MARKET_KEY_IPE: AF_K_MARKET_KEY_IPE_NAME,
                       AF_K_MARKET_KEY_NYBOT: AF_K_MARKET_KEY_NYBOT_NAME,
                       
                       AF_K_MARKET_KEY_SGE: AF_K_MARKET_KEY_SGE_NAME,
                       AF_K_MARKET_KEY_SHFE: AF_K_MARKET_KEY_SHFE_NAME,
//                       AF_K_MARKET_KEY_BOCE: AF_K_MARKET_KEY_BOCE_NAME,
                       AF_K_MARKET_KEY_YRDCE: AF_K_MARKET_KEY_YRDCE_NAME,
                         
                       AF_K_MARKET_KEY_TJPME: AF_K_MARKET_KEY_TJPME_NAME,
                       AF_K_MARKET_KEY_PMEC: AF_K_MARKET_KEY_PMEC_NAME,
                       AF_K_MARKET_KEY_TMRE: AF_K_MARKET_KEY_TMRE_NAME,
                         
                       AF_K_MARKET_KEY_HBOT: AF_K_MARKET_KEY_HBOT_NAME,
                       AF_K_MARKET_KEY_DYYCE:AF_K_MARKET_KEY_DYYCE_NAME,
                       AF_K_MARKET_KEY_BJBCE: AF_K_MARKET_KEY_BJBCE_NAME,
                         
                       AF_K_MARKET_KEY_SZPEC: AF_K_MARKET_KEY_SZPEC_NAME,
                       AF_K_MARKET_KEY_BPEX: AF_K_MARKET_KEY_BPEX_NAME,
                       AF_K_MARKET_KEY_XMPEX: AF_K_MARKET_KEY_XMPEX_NAME,
                         
                       AF_K_MARKET_KEY_CCDPT: AF_K_MARKET_KEY_CCDPT_NAME,
                       AF_K_MARKET_KEY_HNCEC: AF_K_MARKET_KEY_HNCEC_NAME,
                       AF_K_MARKET_KEY_JZMEX: AF_K_MARKET_KEY_JZMEX_NAME,
                         
                       AF_K_MARKET_KEY_QDGJ: AF_K_MARKET_KEY_QDGJ_NAME,
                       AF_K_MARKET_KEY_HXCE: AF_K_MARKET_KEY_HXCE_NAME,
                       AF_K_MARKET_KEY_HFCE: AF_K_MARKET_KEY_HFCE_NAME,
                         AF_K_MARKET_KEY_WJYBK:AF_K_MARKET_KEY_WJYBK_NAME,
                         AF_K_MARKET_KEY_JSCAEE:AF_K_MARKET_KEY_JSCAEE_NAME,
                         AF_K_MARKET_KEY_NJSCAE:AF_K_MARKET_KEY_NJSCAE_NAME,
                         AF_K_MARKET_KEY_CNSCEE:AF_K_MARKET_KEY_CNSCEE_NAME,
                         AF_K_MARKET_KEY_HUAXIACAE:AF_K_MARKET_KEY_HUAXIACAE_NAME,
                         AF_K_MARKET_KEY_HBCPRE:AF_K_MARKET_KEY_HBCPRE_NAME,
                         AF_K_MARKET_KEY_ZNYPJY:AF_K_MARKET_KEY_ZNYPJY_NAME,
                         AF_K_MARKET_KEY_JINMAJIA:AF_K_MARKET_KEY_JINMAJIA_NAME,
                         AF_K_MARKET_KEY_LNDDWJS:AF_K_MARKET_KEY_LNDDWJS_NAME,
                         AF_K_MARKET_KEY_HJ:AF_K_MARKET_KEY_HJ_NAME,
                         AF_K_MARKET_KEY_SJCTM:AF_K_MARKET_KEY_SJCTM_NAME,
                         AF_K_MARKET_KEY_SHXME:AF_K_MARKET_KEY_SHXME_NAME,
                         AF_K_MARKET_KEY_JZCEC:AF_K_MARKET_KEY_JZCEC_NAME,
                         AF_K_MARKET_KEY_DZCE:AF_K_MARKET_KEY_DZCE_NAME,
                         AF_K_MARKET_KEY_QILUCE:AF_K_MARKET_KEY_QILUCE_NAME,
                         AF_K_MARKET_KEY_BLJYZX:AF_K_MARKET_KEY_BLJYZX_NAME,
                         AF_K_MARKET_KEY_DLPMEC:AF_K_MARKET_KEY_DLPMEC_NAME,
                         AF_K_MARKET_KEY_BECCT:AF_K_MARKET_KEY_BECCT_NAME,
                         AF_K_MARKET_KEY_NCCE:AF_K_MARKET_KEY_NCCE_NAME,
                         AF_K_MARKET_KEY_CJMEX:
                             AF_K_MARKET_KEY_CJMEX_NAME
                         
                       };
    return marketExcodeDict;
}

- (NSString*)nameWithExcode:(NSString*)excode{
    NSString *name = @"";
    name = [[self marketExcodeDict] objectForKey:excode];
    return name;
}

// 行情种类列表 http url
-(NSString*)marketListUrlWithExcode:(NSString*)excode{
    
    NSDictionary *unixTimeDict = [[AppSetting manager] httpUnixTime];
    httpUnixTime = [unixTimeDict objectForKey:@"time"];
    httpUnixTimeKey = [unixTimeDict objectForKey:@"time_key"];
    
    NSString *key_str = [NSString stringWithFormat:@"%@%@%@%@", excode, httpUnixTimeKey, AF_K_MARKET_TOKEN, AF_K_MARKET_MD5_KEY];
    NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
    return [NSString stringWithFormat:AF_K_MARKET_URL_LIST, excode, httpUnixTime, AF_K_MARKET_TOKEN, md5];
}



//邮币卡列表借口

-(NSString *)BikamarketListUrlWithExcode:(NSString*)excode{
    NSDictionary *unixTimeDict = [[AppSetting manager] httpUnixTime];
    httpUnixTime = [unixTimeDict objectForKey:@"time"];
    httpUnixTimeKey = [unixTimeDict objectForKey:@"time_key"];
    
    NSString *key_str = [NSString stringWithFormat:@"%@%@%@%@", excode, httpUnixTimeKey, AF_Bika_MARKET_TOKEN, AF_Bika_MARKET_MD5_KEY];
    NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
    return [NSString stringWithFormat:AF_Bika_MARKET_URL_LIST, excode, httpUnixTime, AF_Bika_MARKET_TOKEN, md5];
}

// 获取 kind 行情列表
- (NSArray*)listData{
    return listDataArray;
}

//- (NSArray*)marketListDataWithExcode:(NSString*)excode{
//    if (allKindDictionary == nil) {
//        return nil;
//    }
//
//    NSArray *kindList = [allKindDictionary objectForKey:excode];
//    return kindList;
//}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - list Data Load With 【excode】
////////////////////////////////////////////////////////////////////////////////
- (void)listDataLoadWithExcode:(NSString*)excode withMarketHost:(NSString *)host{
    if ([excode isEqualToString:AF_K_MARKET_KEY_CUSTOM]) {
        [self marketSelfCodeDataLoad:host];
    } else {
        [self marketDataLoadWithExcode:excode withMarketHost:host];
    }
}



- (void)marketDataLoadWithExcode:(NSString*)excode withMarketHost:(NSString *)host {
    
    // 缓存数据
    // [S] 如果不是刷新，则 判断 是否已经存在数据
//    if (allKindDictionary != nil) {
//        NSMutableArray *kindList = [allKindDictionary objectForKey:key];
//        if (kindList) {
//            [self kindDataLoadWithKeyEnd];
//            NSLog(@" key = %@ data has loaded ", key);
//            return;
//        }
//    }
    // [E]

    NSString *urlStr = nil;
    if([host isEqualToString:HTmmarket]){
        urlStr = [self marketListUrlWithExcode:excode];
    }else if([host isEqualToString:Wenmarket]){
        urlStr = [self BikamarketListUrlWithExcode:excode];
    }
    NSURL *url = [NSURL URLWithString:urlStr];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置超时时间(秒)
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
    
    //支持https
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    [manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (listDataArray == nil) {
            listDataArray = [NSMutableArray array];
        }
        
        if ([responseObject isKindOfClass:[NSArray class]]){
            if (listDataArray.count > 0) {
                [listDataArray removeAllObjects];
            }
            [listDataArray addObjectsFromArray:(NSArray*)responseObject];
        }
        
        [self listDataLoadWithExcodeEnd];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        listDataArray = [NSMutableArray array];
        [self listDataLoadWithExcodeEnd];
    }];
    
    
  
}

-(void)listDataLoadWithExcodeEnd {
    if ([self.listDataDelegate respondsToSelector:@selector(marketListDataLoadEnd)]) {
        [self.listDataDelegate marketListDataLoadEnd];
    }
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - 自选种类 列表 数据
////////////////////////////////////////////////////////////////////////////////
// 返回 自选 数据
- (NSArray*)marketCustomCodeData{
    return customCodeListArray;
}

- (NSString*)marketCustomCode{
    return marketSelfCode;
}

- (NSString*)marketCustomExcodeWithCode:(NSString*)_code{
    if (customCodeExcodeDict == nil) {
        return nil;
    }
    return [customCodeExcodeDict objectForKey:_code];
}

// 加载自选数据
- (void)marketSelfCodeDataLoad:(NSString *)host{
    
    customCodeListArray = nil;
    customCodeListArray = [NSMutableArray array];
    
    customCodeExcodeDict = nil;
    customCodeExcodeDict = [NSMutableDictionary dictionary];
    
    marketSelfCode = @"";
    
    NSString *_custome = @"";
    NSString *_excode = @"";
    NSString *_codes = @"";
    
    // 获取所有自选Code
    NSMutableArray *customCodeArray = nil;
    if([host isEqualToString:HTmmarket]){
    customCodeArray =[[AFDbManager dbManager] selectAllData];
    }else if([host isEqualToString:Wenmarket]){
        customCodeArray =[[AFDbManager dbManager] selectAllBikaData];
    }
    if(customCodeArray == nil || [customCodeArray count] <= 0){
        [self marketSelfCodeDataLoadEnd];
        return;
    }
    
    NSDictionary *_dict = nil;
    for(int i = [customCodeArray count] - 1; i >= 0; i--){
        _dict = [customCodeArray objectAtIndex:i];
        
        _excode = [_dict objectForKey:@"excode"];
        _codes = [_dict objectForKey:@"code"];
        
        [customCodeExcodeDict setValue:_excode forKey:_codes];
        
        if (i == [customCodeArray count] - 1){
            _custome = [_custome stringByAppendingString:_excode];
            _custome = [_custome stringByAppendingString:@"|"];
            _custome = [_custome stringByAppendingString:_codes];
            
            marketSelfCode = [marketSelfCode stringByAppendingString:_codes];
        } else {
            _custome = [_custome stringByAppendingString:@","];
            _custome = [_custome stringByAppendingString:_excode];
            _custome = [_custome stringByAppendingString:@"|"];
            _custome = [_custome stringByAppendingString:_codes];
            
            marketSelfCode = [marketSelfCode stringByAppendingString:@"|"];
            marketSelfCode = [marketSelfCode stringByAppendingString:_codes];
        }
    }
    
    NSDictionary *unixTimeDict = [[AppSetting manager] httpUnixTime];
    httpUnixTime = [unixTimeDict objectForKey:@"time"];
    httpUnixTimeKey = [unixTimeDict objectForKey:@"time_key"];
    NSString *urlStr  = nil;
    if([host isEqualToString:HTmmarket]){
    
    NSString *key_str = [NSString stringWithFormat:@"custom%@%@%@", httpUnixTimeKey, AF_K_MARKET_TOKEN, AF_K_MARKET_MD5_KEY];
    NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
    urlStr = [NSString stringWithFormat:AF_K_MARKET_URL_CUSTOM, _custome, httpUnixTime, AF_K_MARKET_TOKEN, md5];
        
    }else if([host isEqualToString:Wenmarket]){
        
        NSString *key_str = [NSString stringWithFormat:@"custom%@%@%@", httpUnixTimeKey, AF_Bika_MARKET_TOKEN, AF_Bika_MARKET_MD5_KEY];
        NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
        urlStr = [NSString stringWithFormat:AF_Bika_MARKET_URL_CUSTOM, _custome, httpUnixTime, AF_Bika_MARKET_TOKEN, md5];
        
    }
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置超时时间(秒)
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
    
    //支持https
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    
    [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]){
            [customCodeListArray addObjectsFromArray:(NSArray *)responseObject];
        }
        
        [self marketSelfCodeDataLoadEnd];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [self marketSelfCodeDataLoadEnd];
    }];
    
    
}

-(void)marketSelfCodeDataLoadEnd{
    if ([self.listDataDelegate respondsToSelector:@selector(marketSelfCodeDataLoadEnd)]) {
        [self.listDataDelegate marketSelfCodeDataLoadEnd];
    }
}

-(BOOL)marketSelfCodeIsChange:(NSString *)host{
    
    // 获取所有自选Code
    NSMutableArray *customCodeArray = nil;
    
    if([host isEqualToString:HTmmarket]){
    customCodeArray = [[AFDbManager dbManager] selectAllData];
    }else if([host isEqualToString:Wenmarket]){
        customCodeArray = [[AFDbManager dbManager] selectAllBikaData];
    }
    if(customCodeArray == nil || [customCodeArray count] <= 0){
        if (customCodeListArray != nil && [customCodeListArray count] > 0) {
            [customCodeListArray removeAllObjects];
        }
        return YES;
    }

    if (customCodeListArray == nil || [customCodeListArray count] <=0) {
        return NO;
    }

    if ([customCodeListArray count] == [customCodeArray count]) {
        return NO;
    }
    
    int count = (int)[customCodeArray count];

    NSString *code;
    NSString *code2;
    BOOL isExist = NO;
    
    int m_count = (int)[customCodeListArray count];
    for (int m = (m_count - 1); m >= 0; m--) {
        
        isExist = NO;
        
        code = [[customCodeListArray objectAtIndex:m] objectForKey:AF_K_MARKET_CODE];
        for (int i = 0; i < count; i++) {
            code2 = [[customCodeArray objectAtIndex:i] objectForKey:@"code"];
            if ([code isEqualToString:code2]) {
                isExist = YES;
                break;
            }
        }
        if (!isExist) {
            [customCodeListArray removeObjectAtIndex:m];
        }
    }
    
//    [customCodeListArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        
//        isExist = NO;
//        code = [obj objectForKey:AF_K_MARKET_CODE];
//
//        for (int i = 0; i < count; i++) {
//            code2 = [[customCodeArray objectAtIndex:i] objectForKey:@"code"];
//            if ([code isEqualToString:code2]) {
//                isExist = YES;
//                break;
//            }
//        }
//        if (!isExist) {
//            [customCodeListArray removeObjectAtIndex:idx];
//        }
//    }];
    
    return YES;
}

////////////////////////////////////////////////////////////////////////////////
//****************************************************************************//
////////////////////////////////////////////////////////////////////////////////
#pragma mark - ========== 分时图 数据 ========== 

// 行情种类列表 http url
-(NSString*)timeDataUrlWithExcode:(NSString*)excode code:(NSString*)code{
    
    NSDictionary *unixTimeDict = [[AppSetting manager] httpUnixTime];
    httpUnixTime = [unixTimeDict objectForKey:@"time"];
    httpUnixTimeKey = [unixTimeDict objectForKey:@"time_key"];
    
    NSString *key_str = [NSString stringWithFormat:@"%@%@%@%@", excode, httpUnixTimeKey, AF_K_MARKET_TOKEN, AF_K_MARKET_MD5_KEY];
    NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
    return [NSString stringWithFormat:AF_K_MARKET_URL_TIME, excode, code, httpUnixTime, AF_K_MARKET_TOKEN, md5];
}

// 邮币卡行情种类列表 http url
-(NSString*)BikatimeDataUrlWithExcode:(NSString*)excode code:(NSString*)code{
    
    NSDictionary *unixTimeDict = [[AppSetting manager] httpUnixTime];
    httpUnixTime = [unixTimeDict objectForKey:@"time"];
    httpUnixTimeKey = [unixTimeDict objectForKey:@"time_key"];
    
    NSString *key_str = [NSString stringWithFormat:@"%@%@%@%@", excode, httpUnixTimeKey, AF_Bika_MARKET_TOKEN, AF_Bika_MARKET_MD5_KEY];
    NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
    return [NSString stringWithFormat:AF_Bika_MARKET_URL_TIME, excode, code, httpUnixTime, AF_Bika_MARKET_TOKEN, md5];
}

// 根据 kindType code 获取 分时数据
- (void)timeDataLoadWithExcode:(NSString*)excode code:(NSString*)code withHost:(NSString *)host{
    // [S]异步请求 asynchronism
    dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // dispatch your task in background
    dispatch_async(q, ^{
        
        NSString *urlString = nil;
        if([host isEqualToString:HTmmarket]){
         urlString =  [self timeDataUrlWithExcode:excode code:code];
        }else if([host isEqualToString:Wenmarket]){
        
        urlString = [self BikatimeDataUrlWithExcode:excode code:code];
        }
        NSLog(@" timeDataLoadWithListType urlString = %@", urlString);
        
        NSString *httpReturnStr = [[AFNetManager manager] httpRequest:urlString];
        
        // 回到主线程,更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //NSLog(@"server return =%@=", self.httpReturnStr);
            
            if ([httpReturnStr isEqualToString:@""]) {
                NSLog(@"-- server return 空数据--");
            } else {
                //NSLog(@"self.httpReturnStr = %@",self.httpReturnStr);
                
                NSData *jsondata =[httpReturnStr dataUsingEncoding:NSUTF8StringEncoding];
                //NSLog(@"self.httpReturnStr = %@", self.httpReturnStr);
                NSError *error = nil;
                id jsonObject =[NSJSONSerialization
                                JSONObjectWithData:jsondata //1
                                options:kNilOptions
                                error:&error];
                
                //NSLog(@"jsonObject = %@", jsonObject);
                //NSLog(@"error= %@", error);
                
                if (jsonObject != nil && error == nil){
                    if ([jsonObject isKindOfClass:[NSDictionary class]]){
                        
                    } else if ([jsonObject isKindOfClass:[NSArray class]]){
                        
                        [[AFMarketData data] initServerTimeListArray:(NSArray *)jsonObject];
                        
                        
                        NSLog(@"------- serverTimeListArray = %i",(int)[[[AFMarketData data] serverTimeListArray] count]);
                    }  else {
                        //NSLog(@"An error happened while deserializing the JSON data.");
                    }
                }
            }
           
           // 分时数据 获取完成后 回掉 
           if ([self.detaileDataDelegate respondsToSelector:@selector(marketTimeDataLoadEnd)]) {
               [self.detaileDataDelegate marketTimeDataLoadEnd];
           }
        });
    });
    // [E]
}


////////////////////////////////////////////////////////////////////////////////
//****************************************************************************//
////////////////////////////////////////////////////////////////////////////////
#pragma mark - ========== k线图 数据 ========== 

// k线数据
#pragma mark - K line draw line type and count

// 行情种类列表 http url
-(NSString*)klineDataUrlWithExcode:(NSString*)excode code:(NSString*)code type:(NSString*)type{
    
    NSDictionary *unixTimeDict = [[AppSetting manager] httpUnixTime];
    httpUnixTime = [unixTimeDict objectForKey:@"time"];
    httpUnixTimeKey = [unixTimeDict objectForKey:@"time_key"];
    
    NSString *key_str = [NSString stringWithFormat:@"%@%@%@%@", excode, httpUnixTimeKey, AF_K_MARKET_TOKEN, AF_K_MARKET_MD5_KEY];
    NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
    return [NSString stringWithFormat:AF_K_MARKET_URL_KLINE, excode, code, type, httpUnixTime, AF_K_MARKET_TOKEN, md5];
}

// 邮币卡行情种类列表 http url
-(NSString*)BikaklineDataUrlWithExcode:(NSString*)excode code:(NSString*)code type:(NSString*)type{
    
    NSDictionary *unixTimeDict = [[AppSetting manager] httpUnixTime];
    httpUnixTime = [unixTimeDict objectForKey:@"time"];
    httpUnixTimeKey = [unixTimeDict objectForKey:@"time_key"];
    
    NSString *key_str = [NSString stringWithFormat:@"%@%@%@%@", excode, httpUnixTimeKey, AF_Bika_MARKET_TOKEN, AF_Bika_MARKET_MD5_KEY];
    NSString *md5 = [[AFUtils md5:key_str] lowercaseString];
    return [NSString stringWithFormat:AF_Bika_MARKET_URL_KLINE, excode, code, type, httpUnixTime, AF_Bika_MARKET_TOKEN, md5];
}

- (void)kLineDataLoadWithExcode:(NSString*)excode code:(NSString*)code klineType:(NSString*)klineType with:(NSString *)host{
    
    NSMutableArray *klineArray = [NSMutableArray array];

    // [S]异步请求 asynchronism
    dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // dispatch your task in background
    dispatch_async(q, ^{
        
        NSString *urlString = nil;
        if([host isEqualToString:HTmmarket]){
        urlString = [self klineDataUrlWithExcode:excode code:code type:klineType];
        }else if([host isEqualToString:Wenmarket]){
           urlString =  [self BikaklineDataUrlWithExcode:excode code:code type:klineType];
        }
        
        NSLog(@"kLineDataLoad urlString = %@", urlString);
        
        AFNetManager *netManager = [[AFNetManager alloc] init];
        NSString *httpReturnStr = [netManager httpRequest:urlString];
        
        // 回到主线程,更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //NSLog(@"server return =%@=", self.httpReturnStr);
            
            if ([httpReturnStr isEqualToString:@""]) {
                NSLog(@"-- server return 空数据--");
            } else {
                //NSLog(@"self.httpReturnStr = %@",self.httpReturnStr);
                
                NSData *jsondata =[httpReturnStr dataUsingEncoding:NSUTF8StringEncoding];
                //NSLog(@"self.httpReturnStr = %@", self.httpReturnStr);
                NSError *error = nil;
                id jsonObject =[NSJSONSerialization
                                JSONObjectWithData:jsondata //1
                                options:kNilOptions
                                error:&error];
                
                //NSLog(@"jsonObject = %@", jsonObject);
                //NSLog(@"error= %@", error);

                if (jsonObject != nil && error == nil){
                    if ([jsonObject isKindOfClass:[NSDictionary class]]){
                        
                    } else if ([jsonObject isKindOfClass:[NSArray class]]){

                        [klineArray addObjectsFromArray:(NSArray *)jsonObject];
                        
                        NSLog(@" klineArray count = %i", (int)[klineArray count]);
                        
                        //[[MarketData data] initServerKLineListArray:(NSArray *)jsonObject isLastKLine:NO];
                    }  else {
                        //NSLog(@"An error happened while deserializing the JSON data.");
                    }
                }

                if ([self.detaileDataDelegate respondsToSelector:@selector(marketKLineDataLoadEnd:)]) {
                   [self.detaileDataDelegate marketKLineDataLoadEnd:klineArray];
                }
            }
            //[self stopDataLoading];
        });
    });
    // [E]
}

////////////////////////////////////////////////////////////////////////////////
//****************************************************************************//
////////////////////////////////////////////////////////////////////////////////
#pragma mark - ========== List Data Refresh With UDP Data ==========

-(void)listDataRefershWithUdpData:(NSDictionary*)udpDict {
    
    // UDP Data
    // {"ExCode":"WGJS","Code":"XAU","QuoteTime":"1413872638","Last":"1249.17",
    // "Open":"1246.66","High":"1250.27","Low":"1245.10","Volume":"1","LastClose":"1246.60","Buy":"1249.17","Sell":"1249.44"}
    
    /* List Data
     Buy = "113.0160";
     Code = CHFJPY;
     Decimal = 2;
     Draw = 288;
     End = "06:00";
     High = "113.3310";
     Last = "113.0160";
     LastClose = "113.3760";
     Low = "112.9160";
     Middle = "18:00";
     Name = "\U745e\U90ce\U65e5\U5143";
     Open = "113.3960";
     Order = 27;
     QuoteTime = 1413872745;
     Sell = "113.0500";
     Start = "06:00";
     UpDown = "-0.3600";
     UpDownRate = "-0.3600";
     Volume = "15580.0000";
     */
    
    // 行情列表数据刷新
    if (listDataArray != nil &&  udpDict != nil) {
        //NSLog(@" list udp data ");
        
        tempUdpCode = [udpDict objectForKey:AF_K_MARKET_CODE];
        
        int count = (int)[listDataArray count];
        for (int i = 0; i < count; i++) {
            tempDict = [listDataArray objectAtIndex:i];
            
            tempCode = [tempDict objectForKey:AF_K_MARKET_CODE];
            
            if ([tempCode isEqual:tempUdpCode]) {

                tempUdpLast = [udpDict objectForKey:AF_K_MARKET_LAST];
                tempUdpHigh = [udpDict objectForKey:AF_K_MARKET_HIGH];
                tempUdpLow = [udpDict objectForKey:AF_K_MARKET_LOW];
                tempUdpQuoteTime = [udpDict objectForKey:AF_K_MARKET_QUOTETIME];
                
                NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
                [newDict addEntriesFromDictionary:tempDict];
                
                [newDict setValue:tempUdpLast forKey:AF_K_MARKET_LAST];
                [newDict setValue:tempUdpHigh forKey:AF_K_MARKET_HIGH];
                [newDict setValue:tempUdpLow forKey:AF_K_MARKET_LOW];
                [newDict setValue:tempUdpQuoteTime forKey:AF_K_MARKET_QUOTETIME];
                
                [listDataArray removeObjectAtIndex:i];
                [listDataArray insertObject:newDict atIndex:i];
                
                break;
            }
        }
    }

    // 自选列表数据刷新
    if (customCodeListArray != nil &&  udpDict != nil) {
        //NSLog(@" self list udp data ");
        
        tempUdpCode = [udpDict objectForKey:AF_K_MARKET_CODE];
        
        int count = (int)[customCodeListArray count];
        for (int i = 0; i < count; i++) {
            tempDict = [customCodeListArray objectAtIndex:i];
            
            tempCode = [tempDict objectForKey:AF_K_MARKET_CODE];
            
            if ([tempCode isEqual:tempUdpCode]) {

                tempUdpLast = [udpDict objectForKey:AF_K_MARKET_LAST];
                tempUdpHigh = [udpDict objectForKey:AF_K_MARKET_HIGH];
                tempUdpLow = [udpDict objectForKey:AF_K_MARKET_LOW];
                tempUdpQuoteTime = [udpDict objectForKey:AF_K_MARKET_QUOTETIME];
                
                
                NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
                [newDict addEntriesFromDictionary:tempDict];
                
                [newDict setValue:tempUdpLast forKey:AF_K_MARKET_LAST];
                [newDict setValue:tempUdpHigh forKey:AF_K_MARKET_HIGH];
                [newDict setValue:tempUdpLow forKey:AF_K_MARKET_LOW];
                [newDict setValue:tempUdpQuoteTime forKey:AF_K_MARKET_QUOTETIME];
                
                
                [customCodeListArray removeObjectAtIndex:i];
                [customCodeListArray insertObject:newDict atIndex:i];
                
                break;
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
//****************************************************************************//
////////////////////////////////////////////////////////////////////////////////
#pragma mark - ========== Data Destroy ==========
-(void)listDataDestroy{
    listDataArray = nil;
}


-(void)customDataDestroy{
    customCodeListArray = nil;
}

@end
